package com.xiaozhengkeji.springboot.frame.easy.api;

import com.xiaozhengkeji.springboot.frame.easy.Bean.ResponseBean;
import com.xiaozhengkeji.springboot.frame.easy.entity.SysMainMenu;
import com.xiaozhengkeji.springboot.frame.easy.entity.SysSubMenu;
import com.xiaozhengkeji.springboot.frame.easy.entity.SysUser;
import com.xiaozhengkeji.springboot.frame.easy.security.JwtTokenUtil;
import com.xiaozhengkeji.springboot.frame.easy.service.SysMainMenuService;
import com.xiaozhengkeji.springboot.frame.easy.service.SysSubMenuService;
import com.xiaozhengkeji.springboot.frame.easy.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/public/menu")
public class MenuApi {
    @Autowired
    private SysMainMenuService sysMainMenuService;
    @Autowired
    private SysSubMenuService sysSubMenuService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private SysUserService sysUserService;


    @GetMapping("/all")
    @PreAuthorize(value = "isAuthenticated()")
    public ResponseBean getAllMenus(@RequestHeader String Token) {
        String username = jwtTokenUtil.getUsernameFromToken(Token.substring("Bearer ".length()));
        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        sysUser = sysUserService.queryAll(sysUser).get(0);
        ArrayList<SysMainMenu> mainMenus = new ArrayList<>();
        //主目录
        List<SysMainMenu> sysMainMenuList = sysMainMenuService.queryAll(new SysMainMenu());
        for (SysMainMenu sysMainMenu : sysMainMenuList) {
            if (sysMainMenu.getRole().equalsIgnoreCase("ROLE_def")) {
                SysSubMenu sysSubMenu = new SysSubMenu();
                sysSubMenu.setMid(sysMainMenu.getId());
                sysMainMenu.setSysSubMenu(sysSubMenuService.queryAll(sysSubMenu));
            }
            if (sysMainMenu.getRole().equalsIgnoreCase(sysUser.getUserRole())) {
                SysSubMenu sysSubMenu = new SysSubMenu();
                sysSubMenu.setMid(sysMainMenu.getId());
                sysMainMenu.setSysSubMenu(sysSubMenuService.queryAll(sysSubMenu));
            }
            mainMenus.add(sysMainMenu);
        }
        return new ResponseBean(200, "ok", mainMenus);
    }
}
